package leetcode.tree;

public class Lc1327 {
    int ans = 0;
    public int longestZigZag(TreeNode root) {
        getAns(root, -1, 1);
        return ans;
    }
    private void getAns(TreeNode node, int dir, int cnt) {
        if (node == null) return;
        if (node.left != null) {
            if (dir == 0) {
                getAns(node.left, 0, 2); //方向没变
            } else if (dir == 1) {//上次往右，这次往左
                ans = Math.max(ans, cnt);
                getAns(node.left, 0, cnt + 1);
            } else { //dir == -1
                ans = Math.max(ans, 1);
                getAns(node.left, 0, 2); //第二个节点
            }
        }
        if (node.right != null) {
            if (dir == 0) {//上次往左，这次往右
                ans = Math.max(ans, cnt);
                getAns(node.right, 1, cnt + 1);
            } else if (dir == 1) { //这次还是往右,没有变化
                getAns(node.right, 1, 2);
            } else {
                ans = Math.max(ans, 1);
                getAns(node.right, 1, 2); //第二个节点
            }
        }
    }
}
